package com.xinfan.io.inputstream;


import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Author xin
 * @Date 2022/6/8 10:52
 * @Version 1.0
 */
public class InputStream_ {
    public static void main(String[] args) {


    }


    /**
     * 读取单个字节 效率比较低
     * ----------->read(byte[] b)
     */
    @Test
    public void read1() {
        String path = "G:\\桌面\\test.txt";
        FileInputStream fileInputStream = null;
        int readData = 0;

        try {
            fileInputStream = new FileInputStream(path);

            while ((readData = fileInputStream.read()) != -1) {//每次向后读一个 所以必须放在判断条件里面
                System.out.print((char) (readData));//utf-8 三个字节为一个字符  所以会中文乱码
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * read(byte[] b)
     */
    @Test
    public void read2() {
        String path = "G:\\桌面\\test.txt";
        FileInputStream fileInputStream = null;

        byte[] buf = new byte[3];
        int length = 0;

        try {
            fileInputStream = new FileInputStream(path);

            while ((length = fileInputStream.read(buf)) != -1) {
                System.out.print(new String(buf,0,length));
                /*System.out.print(new String(buf));//不截取长度最后一次会填入之前的值 不会自动清空
                System.out.println();*/
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
